Skip to content

Fetch Race Condition

In this challenge, you'll attempt to solve a real-world bug I ran into.

I describe the problem in this brief intro video:

Difficulty

This is a very hard problem. Unless you have extensive React experience, you probably won't be able to solve it.

Rules

  • Feel free to google anything you'd like.
  • You're not allowed to install any additional third-party dependencies.

Playground

Code Playground

import React from 'react';

const ENDPOINT =
'https://jor-test-api.vercel.app/api/get-price-for-quantity';

function App() {
const [quantity, setQuantity] = React.useState(1);
const [price, setPrice] = React.useState(null);
const id = React.useId();

React.useEffect(() => {
async function runEffect() {
const response = await fetch(
`${ENDPOINT}?quantity=${quantity}`
);
const data = await response.json();
setPrice(data.price);
}

runEffect();
}, [quantity]);

return (
<div className="wrapper">
<img
src="https://courses.joshwcomeau.com/images/joy-of-react-mascot.png"
alt=""
className="mascot"
/>
<form>
<div className="row">
<label htmlFor={id}>Quantity:</label>
<input
id={id}
type="number"
min={1}
max={50}
value={quantity}
onChange={(event) => {
setQuantity(event.target.value);
}}
/>
</div>

<button>
Buy {quantity} unit(s) for ${price}
</button>
</form>
</div>
);
}

export default App;

My attempt